package com.mediacloud.app.newsmodule.fragment;


import android.content.Context;
import android.os.Build;
import android.os.MessageQueue;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.GAsyncLayoutInflater;
import com.mediacloud.app.newsmodule.fragment.ws.WS24ListFragment2;
import com.utils.InflateTimeLogTools;
import com.zimeiti.activity.TabListFragment;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 提前预加载，预防ViewPaper滚动时即使加载引起的卡顿
 * 为避免界面同时爆发请求同类型FragmentView， 采取LinkedList存储，适应系统得爆发要求
 * <p>
 * Create by Guang
 */
public class FragmentPreInflateHelper {
    private static HashMap<String, LinkedList<View>> preInflateViewList = new HashMap<>();
    private static Context mContext;
    private static volatile FragmentPreInflateHelper adapterPreInflateHelper;
    private static GAsyncLayoutInflater asyncLayoutInflater;

    private static ExecutorService pools;

    private FragmentPreInflateHelper() {
    }

    public static void onDestoryView() {
        try {
            preInflateViewList.clear();
            mContext = null;
            asyncLayoutInflater.destory();
            asyncLayoutInflater = null;
            adapterPreInflateHelper = null;
            pools.shutdownNow();
        }catch (Exception e){

        }
    }

    private FragmentPreInflateHelper(Context context) {
        mContext = context;
        asyncLayoutInflater = new GAsyncLayoutInflater(mContext);
        pools = Executors.newCachedThreadPool();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            context.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    preInflateView();
                    return false;
                }
            });
        } else {
            preInflateView();
        }
    }

    public static FragmentPreInflateHelper getInstance(Context context) {
        if (adapterPreInflateHelper == null) {

            synchronized (FragmentPreInflateHelper.class) {
                if (adapterPreInflateHelper == null) {
                    adapterPreInflateHelper = new FragmentPreInflateHelper(context);
                }
            }
        }
        return adapterPreInflateHelper;
    }

    public View containsKey(String unionKey) {
        if (preInflateViewList.containsKey(unionKey)) {
            LinkedList<View> views = preInflateViewList.get(unionKey);
            if (views.size() > 1) {
                return views.pop();
            } else {
                return null;
            }
        }
        return null;
    }

    public View getView(int layoutId, Class clazz) {
        if (preInflateViewList.isEmpty() || mContext == null) {
            return null;
        }
        String unionKey = clazz.getName();
        LinkedList<View> views = preInflateViewList.get(unionKey);
        if (preInflateViewList.containsKey(unionKey)) {
            if (views.size() > 0) {
                //只允许通过预加载的Fragment进行预加载缓冲操作1
                preInflateLoad(layoutId, clazz);
                return views.pop();
            }
        }
        return null;
    }

    public void preInflateView() {
        //基础BaseNewsListFragmentX的布局文件，预加载对性能提升较大
        //preInflateLoad(R.layout.fragment_catalog_itemcontent, BaseNewsListFragmentX.class);
        for (int i = 0; i < 2; i++) {
            //军情Tab内，组件内Fragment
            preInflateLoad(R.layout.ws24_list_fragment2, WS24ListFragment2.class);
        }
        for (int i = 0; i < 4; i++) {
            //军团Tab内，组件内Fragment
            preInflateLoad(R.layout.fragment_tab_news_list, TabListFragment.class);
        }

        //preInflateLoad(R.layout.fragment_ws24, WS24Fragment.class);
        //preInflateLoad(R.layout.fragment_blank_page, NewBlankPageFragment.class);
        //preInflateLoad(R.layout.fragment_blank_page, PaperC.class);
    }

    public void preInflateLoad(int layoutId, final Class fragment) {
        if (mContext == null) {
            return;
        }
        pools.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    asyncLayoutInflater.inflate(layoutId, null, new GAsyncLayoutInflater.OnInflateFinishedListener() {
                        @Override
                        public void onInflateFinished(@NonNull View view, int resid, @Nullable ViewGroup parent) {
                            addPreInflateView(fragment.getName(), view);
                            InflateTimeLogTools.fragmentTimeLogTools("---preinflate-fragment----", System.currentTimeMillis(), fragment);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });

    }

    public void addPreInflateView(String unionKey, View view) {
        if (mContext == null) {
            return;
        }

        if (preInflateViewList.containsKey(unionKey)) {
            preInflateViewList.get(unionKey).push(view);
        } else {
            LinkedList<View> views = new LinkedList<>();
            views.push(view);
            preInflateViewList.put(unionKey, views);
        }
    }
}
